package com.example.student.controller;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.common.domain.Result;
import com.example.common.domain.dto.SectionDto;
import com.example.common.domain.pojo.Attendance;
import com.example.common.domain.pojo.CourseOutline;
import com.example.common.domain.pojo.Homework;
import com.example.common.domain.pojo.Section;
import com.example.common.domain.pojo.TypeHandler.JsonToObject;
import com.example.student.service.AttendanceService;
import com.example.student.service.CourseOutlineService;
import com.example.student.service.HomeworkService;
import com.example.student.service.SectionService;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@Api(value = "学生端接口", description = "学生查看操作")
@RestController
@RefreshScope//时时刷新配置信息
@Slf4j  //日志  log.info("登录日志测试：");
@RequestMapping("/students")
@RequiredArgsConstructor
public class SelectController {
    @Autowired
    private HomeworkService homeworkService;
    @Autowired
    private AttendanceService attendanceService;
    @Autowired
    private CourseOutlineService outlineService;
    @Autowired
    private JsonToObject json;
    @Autowired
    private SectionService sectionService;

    @ApiOperation("查询这个课程的所有作业")
    @GetMapping("/getHomeworkList/{courseId}")
    public Result<Page<Homework>> getHomeworkList(
            @PathVariable String courseId,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize
    ) {
        Page<Homework> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<Homework> queryWrapper = new LambdaQueryWrapper<Homework>()
                .eq(Homework::getCourseId, courseId)
                .orderByDesc(Homework::getStartTime); // 按创建时间倒序

        return Result.success(homeworkService.page(page, queryWrapper));
    }

    @ApiOperation("查询这个课程的所有签到")
    @GetMapping("/getSignInList/{courseId}")
    public Result<Page<Attendance>> getSignInList(@PathVariable String courseId,
                                                  @RequestParam(defaultValue = "1") Integer pageNum,
                                                  @RequestParam(defaultValue = "10") Integer pageSize) {
        Page<Attendance> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<Attendance> queryWrapper = new LambdaQueryWrapper<Attendance>()
                .eq(Attendance::getCourseId, courseId)
                .orderByDesc(Attendance::getStartTime); // 按创建时间倒序

        return Result.success(attendanceService.page(page, queryWrapper));
    }

    @ApiOperation("查询这个课程的课程大纲")
    @GetMapping("/generateOutline/{courseId}")
    public Result<CourseOutline> getCourseOutline(
            @ApiParam(value = "课程ID", required = true)
            @PathVariable String courseId) {
        log.info("获取课程大纲，课程ID：{}", courseId);
        try {
            CourseOutline outline = outlineService.teacherGetChapter(courseId);
            String teachingContentJson = JSONUtil.toJsonStr(outline.getTeachingElements());
            Map<String, List<String>> outlineMapT = json.parseToMapList(teachingContentJson);
            System.out.println(outlineMapT);
            Map<String, List<String>> outlineMap = new ObjectMapper().readValue(
                    teachingContentJson,
                    new TypeReference<Map<String, List<String>>>() {
                    }
            );
            outline.setTeachingContent(outlineMap);
            System.out.println(outlineMap);
            return Result.success(outline);
        } catch (Exception e) {
            log.error("获取课程大纲失败：", e);
            return Result.error("获取课程大纲失败：" + e.getMessage());
        }
    }

    @ApiOperation("根据大纲id获取小节， (小节id 为拼接字符串 课程id+第几个人章（09  11）+第几小节 （ 05  10）)")
    @GetMapping("/getSectionsBySectionId")
    public Result<Section> getSections(
            @ApiParam(value = "课程ID,也是大纲Id", required = true)
            @RequestBody SectionDto sectionDto) {
        String sectionId = sectionDto.getCourseId() + sectionDto.getChapterId() + sectionDto.getSectionId();
        return Result.success(sectionService.getSectionBySectionId(sectionId));
    }


}
